/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.huawei.libyuv.slice;

import com.huawei.libyuv.Libyuv;
import com.huawei.libyuv.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;
import ohos.hiviewdfx.HiLogLabel;
import java.io.IOException;
import java.nio.ByteBuffer;

public class MainAbilitySlice extends AbilitySlice {
    static {
        System.loadLibrary("libyuv");
    }

    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, "[openharmony slice] ");
    private PositionLayout myLayout = new PositionLayout(this);
    private Button mainButton;
    private DependentLayout mDlViewRoot;
    private Image mIvTransition;
    private PixelMap outpixelmap;
    private String distributedFile;
    private static final int CACHE_SIZE = 256 * 1024;
    private static final int IO_END_LEN = -1;
    private static final String RAW_FILE_PATH = "entry/resources/rawfile/";

    public PixelMap createPixelMap(int width, int height)
    {
        PixelMap pixelMap =  null;
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.size = new Size(width,height);
        initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
        initializationOptions.editable = true;
        pixelMap = PixelMap.create(initializationOptions);

        return pixelMap;
    }

    public byte[] bitmapToRgba(PixelMap bitmap) {
        int[] pixels = new int[bitmap.getImageInfo().size.width * bitmap.getImageInfo().size.height];
        byte[] bytes = new byte[pixels.length * 4];
        bitmap.readPixels(pixels, 0, bitmap.getImageInfo().size.width, new ohos.media.image.common.Rect(0, 0, bitmap.getImageInfo().size.width, bitmap.getImageInfo().size.height));

        int i = 0;
        for (int pixel : pixels) {
            // Get components assuming is ARGB
            int A = (pixel >> 24) & 0xff;
            int R = (pixel >> 16) & 0xff;
            int G = (pixel >> 8) & 0xff;
            int B = pixel & 0xff;
            bytes[i++] = (byte) R;
            bytes[i++] = (byte) G;
            bytes[i++] = (byte) B;
            bytes[i++] = (byte) A;
        }
        return bytes;
    }

    public PixelMap bitmapFromRgba(int width, int height, byte[] bytes) {
        int[] pixels = new int[bytes.length / 4];
        int j = 0;

        for (int i = 0; i < pixels.length; i++) {
            int R = bytes[j++] & 0xff;
            int G = bytes[j++] & 0xff;
            int B = bytes[j++] & 0xff;
            int A = bytes[j++] & 0xff;

            int pixel = (A << 24) | (R << 16) | (G << 8) | B;
            pixels[i] = pixel;
        }


        PixelMap bitmap = createPixelMap(width, height);
        bitmap.writePixels(pixels,0,width,new Rect(0,0,width,height));
        return bitmap;
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        ComponentContainer layout = (ComponentContainer) LayoutScatter.getInstance(this).
                parse(ResourceTable.Layout_slice_rotate, null, false);
        mDlViewRoot = (DependentLayout) layout.findComponentById(ResourceTable.Id_dlViewRoot);
        mIvTransition = (Image) layout.findComponentById(ResourceTable.Id_ivRotate);
        mainButton = (Button) layout.findComponentById(ResourceTable.Id_mainButton);

        mainButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry(RAW_FILE_PATH + "test.jpg");
                try {
                    Resource resource = rawFileEntry.openRawFile();
                    ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
                    ImageSource imageSource = ImageSource.create(resource, srcOpts);
                    ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
                    decodingOpts.desiredSize = new Size(0, 0);
                    decodingOpts.desiredRegion = new Rect(0, 0, 0, 0);
                    decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;
                    PixelMap pixelMap = imageSource.createPixelmap(decodingOpts);
                    int h = pixelMap.getImageInfo().size.height;
                    int w = pixelMap.getImageInfo().size.width;
                    long bytes = pixelMap.getPixelBytesNumber();
                    ByteBuffer buf = ByteBuffer.allocate((int) bytes);
                    pixelMap.readPixels(buf);
                    byte[] byteArray = buf.array();
                    byte[] rgbbuffer=new byte[w*h*4];
                    Libyuv.ARGBToRGBA(byteArray, w*4,  rgbbuffer, w*4, w, h);

                    PixelMap drawBm =bitmapFromRgba(pixelMap.getImageInfo().size.width, pixelMap.getImageInfo().size.height, rgbbuffer);
                    mIvTransition.setPixelMap( drawBm);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        super.setUIContent(layout);
    }
    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}
